//
//  SEGEditDetailViewController.m
//  ExcellentHome
//
//  Created by 刘山 on 16/11/22.
//  Copyright © 2016年 陈区. All rights reserved.
//
#import "SEGCompletePesonalInfoViewController.h"
#import "SEGEditDetailViewController.h"

#import "SEGEditDetailViewModel.h"

@interface SEGEditDetailViewController () <UITextFieldDelegate, UITextViewDelegate, UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITextField *contentField;
@property (nonatomic, strong) UITextView *contentTextView;
/// 选中性别图标
@property (nonatomic, strong) UIImage *selectImage;
@property (nonatomic, strong)UIView *headView;
@property (nonatomic, strong)UILabel *placeholderLabel;
/// 表格
@property (nonatomic, strong) UITableView *mainTable;

/// viewModel
@property (nonatomic, strong) SEGEditDetailViewModel *viewModel;

@end

@implementation SEGEditDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = kColor_bg;
    
    [self showCustomNavigationBackButton];
    
    switch (self.showType) {
    case EditDetailShowType_UITextField: {
        [self setupUI_UITextField];
    } break;
    case EditDetailShowType_UITextView: {
        [self setupUI_UITextView];
    } break;
    case EditDetailShowType_UITableView: {
        [self setupUI_UITableView];
    }break;

    default:
        break;
    }
}

#pragma mark - Load Data
- (void)seg_loadData {
    [self.viewModel.jobListCommand.executing subscribeNext:^(NSNumber * _Nullable x) {
       if (x.boolValue) {
           [SVProgressHUD show];
       } else {
           [SVProgressHUD dismiss];
       }
    }];
    @weakify(self);
    [[self.viewModel.jobListCommand execute:@""] subscribeNext:^(id  _Nullable x) {
        @strongify(self);
        [self.mainTable reloadData];
    } error:^(NSError * _Nullable error) {
        [SEGAlertView showTmepMessageWithMessage:error.localizedFailureReason];
    }];
}
// 上传所有的信息
- (void)updateAllDataSource {
    @weakify(self);
    [[self.viewModel.updateInfoCommand execute:self.recordProfessionId] subscribeNext:^(NSString *errorMessage) {
        @strongify(self);
        if (errorMessage.length > 0) {
            [SEGAlertView showTmepMessageWithMessage:errorMessage];
        } else {
            // 通知个人页面刷新数据
            [[NSNotificationCenter defaultCenter] postNotificationName:SEGEditUserInfoFinishedNotification object:nil];
            [self ClickToGoBack];
        }
    } error:^(NSError * _Nullable error) {
        [SEGAlertView showTmepMessageWithMessage:error.localizedFailureReason];
    }];
}

#pragma mark - UI
- (void)setupUI_UITableView {
    [self.view addSubview:self.mainTable];
    [_mainTable reloadData];
    switch (self.editType) {
        case EditJobAndMaleType_Male:{
            NSArray* dataSourceArr = @[@{@"key":@"2",@"name":@"男",@"value":@""},
                                       @{@"key":@"1",@"name":@"女",@"value":@""}];
            self.viewModel.dataSourceArr = dataSourceArr;
            break;
        }
        case EditJobAndMaleType_Job:{
            if (self.isFromLogin) {
                [self showCustomNavigationRightButtonWithTitle:@"跳过" image:nil hightlightImage:nil color:kColor_3];
            }
            [self seg_loadData];
            break;
        }
    }
}
- (void)setupUI_UITextField {
    [self showCustomNavigationRightButtonWithTitle:@"保存" image:nil hightlightImage:nil];
    [self.view addSubview:self.contentField];
    [self.contentField becomeFirstResponder];
    [self.contentField mas_makeConstraints:^(MASConstraintMaker* make) {
        make.top.equalTo(self.view).mas_offset(15);
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo(44);
    }];
}
- (void)setupUI_UITextView {
    [self showCustomNavigationRightButtonWithTitle:@"保存" image:nil hightlightImage:nil];
    [self.view addSubview:self.contentTextView];
    [self.contentTextView becomeFirstResponder];
    NSDictionary* attribute = @{ NSFontAttributeName : self.contentTextView.font};
    CGSize textSize = [self.contentTextView.text boundingRectWithSize:CGSizeMake(LYScreenWidth(), 0) options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attribute context:nil].size;
    [self.contentTextView mas_makeConstraints:^(MASConstraintMaker* make) {
        make.top.equalTo(self.view).mas_offset(15);
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo(textSize.height + 15);
    }];
}

#pragma mark - Event
- (void)onNavigationRightButtonClicked:(UIButton *)sender {
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    switch (self.showType) {
    case EditDetailShowType_UITextField: {
        if (self.isNotEmpty) {
            if ([self.contentField.text length] <= 0) {
                [SEGAlertView showTmepMessageWithMessage:@"请输入昵称"];
                return;
            }
            
            if (self.userInfo && [self.userInfo isKindOfClass:[NSDictionary class]] && [[self.userInfo allKeys] containsObject:@"name"]) {
                NSString *value = [self.userInfo valueForKey:@"name"];
                if (value && [value isKindOfClass:[NSString class]] && [value isEqualToString:@"nickName"]) {
                    
                    NSCharacterSet  *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
                    NSString *nickname = [self.contentField.text stringByTrimmingCharactersInSet:set];
                    if (nickname.length <= 0 ) {
                        [SEGAlertView showTmepMessageWithMessage:@"请输入昵称"];
                        return;
                    }
                }
            }
        }
        // 提交昵称的时候 去掉前后空格和回车
        NSString *nickname = self.contentField.text;
        //如果仅仅是去前后空格，用whitespaceCharacterSet
        NSCharacterSet  *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
        nickname = [nickname stringByTrimmingCharactersInSet:set];
        [dict setValue:nickname forKey:@"UITextField"];
    } break;
    case EditDetailShowType_UITextView: {
        NSCharacterSet  *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
        NSString *content = [self.contentTextView.text stringByTrimmingCharactersInSet:set];
        if (self.isNotEmpty) {
            if ([content length] <= 0) {
                [SEGAlertView showTmepMessageWithMessage:@"输入内容不能为空！"];
                return;
            }
        }
        // 用户信息-个人描述整体长度不能超多50个字
        if ([[self.userInfo valueForKey:@"name"] isEqualToString:@"desc"] && [content length] > 50) {
            [SEGAlertView showTmepMessageWithMessage:@"个人描述不能超过50字"];
            return;
        }
        [dict setValue:content forKey:@"UITextView"];
    } break;
    case EditDetailShowType_UITableView:{
        
        //上传所有的信息
        [self updateAllDataSource];
    }
    default:
        break;
    }
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(response_DataWithUserInfo:Params:)]) {
        [self.delegate response_DataWithUserInfo:self.userInfo Params:dict];
        //[self.navigationController popViewControllerAnimated:YES];
    }
}
// 职业选择点击返回逻辑 -- 从哪儿来回哪儿去
- (void)ClickToGoBack {
    // 导航栏跳过的逻辑
    NSArray *arrController = self.navigationController.viewControllers;
    // 主页 -- 完善资料  跳过到主页
    for (UIViewController *vc in arrController) {
        if ([vc isKindOfClass:[NSClassFromString(@"SEGPersonalHomepageViewController") class]]) {
            [self.navigationController popToViewController:arrController[1] animated:YES];//我的主页
        } else if ([vc isKindOfClass:[NSClassFromString(@"SEGMainViewController") class]]) {
            [self.navigationController popToRootViewControllerAnimated:YES];
        }
    }
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    switch (self.editType) {
        case EditJobAndMaleType_Male:{  //性别没有组头
            return 1;
            break;
        }break;
        case EditJobAndMaleType_Job:{   //职业设置组头
            return self.viewModel.dataSourceArr.count;
            break;
        }break;
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    switch (self.editType) {
        case EditJobAndMaleType_Male:{  //性别没有组头
            return self.viewModel.dataSourceArr.count;
            break;
        }break;
        case EditJobAndMaleType_Job:{   //职业设置子节点
            SEGJobMessageModel *model = self.viewModel.myManager.seg_segjobmessagemodel[section];
            NSString *sectionIndex = [NSString stringWithFormat:@"%zd",section];
            if ([self.viewModel.sectionArray containsObject:sectionIndex]) {
                return model.childList.count;
            }else{
                return 0;
            }
        }break;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SEGEditJobAndMaleTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kEditDetailListCellIdentifier];
    if (!cell) {
        cell = [[SEGEditJobAndMaleTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kEditDetailListCellIdentifier];
    }
    switch (self.editType) {
        case EditJobAndMaleType_Male:{
            NSDictionary *dict = _viewModel.dataSourceArr[indexPath.row];
            cell.normalLabel.text = [dict valueForKey:@"name"];
            cell.selectImage.hidden = YES;
            if ([self.recordSex isEqualToString:[dict valueForKey:@"key"]]) {
                cell.selectImage.hidden = NO;
                cell.normalLabel.textColor =kColor_1;
            }
            break;
        }break;
        case EditJobAndMaleType_Job:{
            SEGJobMessageModel *model = self.viewModel.myManager.seg_segjobmessagemodel[indexPath.section];
            SEGJobNodeMessageModel *childModel =  model.childList[indexPath.row];
            cell.nodeLabel.text = childModel.professionName;
            if ([self.viewModel.sectionArray containsObject:model.professionId] && [self.viewModel.cellIndexId isEqualToString:childModel.professionId]) {
                cell.nodeLabel.textColor =kColor_1;
                cell.selectImage.hidden = NO;
            }else{
                cell.nodeLabel.textColor =kColor_1;
                cell.selectImage.hidden = YES;
            }

            if ([self.recordProfessionId isEqualToString:childModel.professionId]) {
                cell.nodeLabel.textColor =kColor_1;
                cell.selectImage.hidden = NO;
            }else{
                cell.nodeLabel.textColor =kColor_1;
                cell.selectImage.hidden = YES;
            }
        }break;
    }
    
    return cell;
}
#pragma mark - UITableViewDelegate
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    SEGJobMessageModel *model = self.viewModel.myManager.seg_segjobmessagemodel[section];
    self.headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, LYScreenWidth(), 44)];
    self.headView.backgroundColor = kColor_W;
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    btn.frame = CGRectMake(0, 0, LYScreenWidth(), 43.5);
    
    [btn setTitle:model.professionName forState:UIControlStateNormal];
    [btn setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
    [btn setTitleColor:kColor_1 forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:15];
    
    [btn setImage:[UIImage imageWithContentsOfFile:SEGPicName(@"btn_list_down")] forState:UIControlStateNormal];
    btn.imageEdgeInsets = UIEdgeInsetsMake(0, LYScreenWidth() - 30, 0, 0);
    btn.tag = section+999;
    [btn addTarget:self action:@selector(headViewClickAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.headView addSubview:btn];
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 43.5, LYScreenWidth(), 0.5)];
    lineView.backgroundColor= kColor_L2;
    [self.headView addSubview:lineView];
    
    if ([self.viewModel.sectionArray containsObject:[NSString stringWithFormat:@"%zd",section]]) {
        [btn setImage:[UIImage imageWithContentsOfFile:SEGPicName(@"btn_list_up")] forState:UIControlStateNormal];
    } else {
        [btn setImage:[UIImage imageWithContentsOfFile:SEGPicName(@"btn_list_down")] forState:UIControlStateNormal];
    }

    return self.headView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    switch (self.editType) {
        case EditJobAndMaleType_Male:{  //性别没有组头
            return 0;
            break;
        }break;
        case EditJobAndMaleType_Job:{   //职业设置子节点
            return 44;
        }break;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 44;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (self.editType) {
        case EditJobAndMaleType_Male:{
            for (int i = 0; i < self.viewModel.dataSourceArr.count; i++) {
                SEGEditJobAndMaleTableViewCell *cell = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
                if (i == indexPath.row) {
                    NSString * sex = [[NSString alloc] init];
                    if ([cell.normalLabel.text isEqualToString:@"男"]) {
                        sex = @"2";
                    }else{
                        sex = @"1";
                    }
                    self.recordSex = sex;
                     [self jobUpdateData:sex];
                }
                else {
                    [cell.selectImage setHidden:YES];
                }
            }
            break;
        }break;
        case EditJobAndMaleType_Job:{
            SEGJobMessageModel *model = self.viewModel.myManager.seg_segjobmessagemodel[indexPath.section];
            self.viewModel.cellIndexId = model.childList[indexPath.row].professionId;
            //记录选中的cell
            self.recordProfessionId = model.childList[indexPath.row].professionId;
            self.viewModel.recordProfessionName = model.childList[indexPath.row].professionName;
            [_mainTable reloadData];
            
            //如果是从登录页的完善资料页跳转而来
            if (self.isFromLogin) { //上传所有的信息
                
                [self updateAllDataSource];
            }else{  //个人资料页职业的点击  --  上传职业信息
                [self jobUpdateData: self.recordProfessionId];
            }
            
        }break;
    }
}
//  上传职业和性别信息
- (void)jobUpdateData:(NSString *)updateData {
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    switch (self.editType) {
        case EditJobAndMaleType_Male:{
            [dict setValue:updateData forKey:@"UITableView_MaleType"];
            break;
        }break;
        case EditJobAndMaleType_Job:{
            [dict setValue:self.recordProfessionId forKey:@"UITableView_JobType"];
            [dict setValue:self.viewModel.recordProfessionName forKey:@"UITableView_JobName"];
            break;
        }break;
    }
    if (self.delegate && [self.delegate respondsToSelector:@selector(response_DataWithUserInfo:Params:)]) {
         [self.delegate response_DataWithUserInfo:self.userInfo Params:dict];
        [self.navigationController popViewControllerAnimated:YES];
    }
   
}
// section展开收缩效果实现
- (void)headViewClickAction:(UIButton *)sender {
    NSString *sectionIndex = [NSString stringWithFormat:@"%zd",sender.tag-999];
    if ([self.viewModel.sectionArray containsObject:sectionIndex]) {
        [self.viewModel.sectionArray removeObject:sectionIndex];
    } else {
        [self.viewModel.sectionArray addObject:sectionIndex];
    }
    [_mainTable reloadData];
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    // 主要是[receiver resignFirstResponder]在哪调用就能把receiver对应的键盘往下收
    [self.contentField resignFirstResponder];
    return YES;
}
- (void)textFieldDidEndEditing:(UITextField *)textField {
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    return YES;
}
- (void)textViewDidChange:(UITextView *)textView {
    NSDictionary *attribute = @{ NSFontAttributeName : self.contentTextView.font };
    CGSize textSize = [self.contentTextView.text boundingRectWithSize:CGSizeMake(LYScreenWidth(), 0) options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attribute context:nil].size;
    [self.contentTextView mas_updateConstraints:^(MASConstraintMaker* make) {
        make.top.equalTo(self.view).mas_offset(15);
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo((textSize.height + 30) > kLYScreenHeight() * 0.45 ? kLYScreenHeight() * 0.45 : (textSize.height + 30));
    }];
    if (self.placeholderLabel) [self.placeholderLabel setHidden:[textView.text length] > 0 ? YES : NO];
}
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    if (text && [text isEqualToString:@"\n"]) {
        [self.contentTextView resignFirstResponder];
        return NO;
    }
    // if ([[textView.text stringByReplacingCharactersInRange:range withString:text] length] > 50) return NO;
    return YES;
}

#pragma mark - Setter
- (void)setShowType:(EditDetailShowType)showType {
    // 移除职业的默认选中状态
    [self.viewModel.sectionArray removeAllObjects];
    
    _showType = showType;
}
#pragma mark - Getter
- (SEGEditDetailViewModel *)viewModel {
    if (!_viewModel) _viewModel = [SEGEditDetailViewModel new];
    return _viewModel;
}
- (UITableView *)mainTable {
    if (!_mainTable) {
        _mainTable = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, LYScreenWidth(), kLYScreenHeight() - kNavigationBarAndStatusBarHeight) style:UITableViewStylePlain];
        _mainTable.backgroundColor = kColor_bg;
        _mainTable.dataSource = self;
        _mainTable.delegate = self;
        _mainTable.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        _mainTable.tableFooterView = [[UIView alloc] init];
        [_mainTable registerClass:[SEGEditJobAndMaleTableViewCell class] forCellReuseIdentifier:kEditDetailListCellIdentifier];
    }
    return _mainTable;
}
- (UITextField *)contentField {
    if (!_contentField) {
        _contentField = [[UITextField alloc] init];
        [_contentField setBackgroundColor:kColor_W];
        _contentField.returnKeyType = UIReturnKeyDone;
        _contentField.clearButtonMode = UITextFieldViewModeAlways;
        _contentField.autoresizingMask = UIViewAutoresizingFlexibleHeight;
        _contentField.font = [UIFont systemFontOfSize:16];
        _contentField.textColor = kColor_1;
        _contentField.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 15, 0)]; //光标右偏移15
        _contentField.leftViewMode = UITextFieldViewModeAlways;
        _contentField.tintColor = kColor_T;
        _contentField.delegate = self;
        _contentField.placeholder = self.placeholder;
        _contentField.text = self.contentText;
    }
    return _contentField;
}
- (UITextView *)contentTextView {
    if (!_contentTextView) {
        _contentTextView = [[UITextView alloc] init];
       [_contentTextView setBackgroundColor:kColor_W];
       _contentTextView.delegate = self;
       _contentTextView.font = [UIFont systemFontOfSize:16];
       _contentTextView.returnKeyType = UIReturnKeyDone;
       _contentTextView.textColor = kColor_1;
       _contentTextView.text = self.contentText;
       _contentTextView.tintColor = kColor_T;
    
       UILabel *lb = [[UILabel alloc] init];
       [lb setText:self.placeholder];
       [lb setTextColor:kColor_3];
       [lb setFont:[UIFont systemFontOfSize:16]];
       lb.textAlignment = NSTextAlignmentCenter;
       self.placeholderLabel = lb;
       [_contentTextView addSubview:self.placeholderLabel];
       [self.placeholderLabel mas_makeConstraints:^(MASConstraintMaker *make) {
           make.left.equalTo(self.contentTextView).offset(10);
           make.top.equalTo(self.contentTextView).offset(8);
       }];
       [self.placeholderLabel setHidden:(self.placeholder && [self.placeholder length] > 0 && self.contentText && [self.contentText length] <= 0) ? NO : YES];
    }
    return _contentTextView;
}

@end
